package com.github.thinwonton.showcase.springboot.security.service;

import com.github.thinwonton.showcase.springboot.security.po.SystemUser;
import com.github.thinwonton.showcase.springboot.security.po.SystemUser_;
import com.github.thinwonton.showcase.springboot.security.repository.SystemUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户服务
 *
 * @author hugo
 * @date 2018/7/12
 */
@Service
public class SystemUserService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private SystemUserRepository systemUserRepository;

    public SystemUser getByUsername(String username) {

        SystemUser systemUser = systemUserRepository.findOne((root, query, cb) -> {

            //存放多种查询条件,实现动态查询
            List<Predicate> predicateList = new ArrayList<>();

            //等于username
            if (username != null) {
                predicateList.add(cb.equal(root.get(SystemUser_.userName), username));
            }

            return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

        });

        return systemUser;
    }
}
